package com.wing.product.strategy;

import com.wing.sell.strategy.BeansUtil;
import org.reflections.Reflections;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @Description: 策略工厂
 * @Project: szgc-enterprise-coding
 * @Package: com.wing.sell.strategy.GenerateSelOrderStrategyFactory
 * @Date: 2024/12/16 10:17
 * @Author: heZhou
 * @Version: 1.0
 */
public class OrderTStrategyFactory {

    /**
     * 私有化构造函数，单例
     */
    private OrderTStrategyFactory() {

    }

    private static class Builder {
        private static final OrderTStrategyFactory payStrategyFactory = new OrderTStrategyFactory();
    }

    /**
     * 获取实例
     * @return
     */
    public static OrderTStrategyFactory getInstance() {
        return Builder.payStrategyFactory;
    }

    // 单例结束

    private static final String PAY_STRATEGY_IMPLEMENTATION_PACKAGE = "com.wing.product.strategy.impl";
    private static final Map<String, Class> STRATEGY_MAP = new HashMap<>();

    // 获取所有order策略
    static {
        Reflections reflections = new Reflections(PAY_STRATEGY_IMPLEMENTATION_PACKAGE);
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(OrderType.class);
        classSet.forEach(aClass -> {
            OrderType payAnnotation = aClass.getAnnotation(OrderType.class);
            STRATEGY_MAP.put(payAnnotation.type(), aClass);
        });
    }

    /**
     * 根据selOrder策略类型获取selOrder策略bean
     *
     * @param type
     * @return
     */
    public static OrderTStrategy getStrategy(String type) {
        // 反射获取selOrder策略实现类clazz
        Class clazz = STRATEGY_MAP.get(type);
        if (StringUtils.isEmpty(clazz)) {
            return null;
        }

        // 通过applicationContext获取bean
        return (OrderTStrategy) BeansUtil.getBean(clazz);
    }
}
